import 'dart:math';

import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:material_dialogs/dialogs.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:tracker/common/widget/common.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/utils/toast_utils.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/log/x_logger.dart';
import '../../../../provider/global_provider.dart';
import '../../../../theme/app_theme.dart';
import '../mixin/record_history_mixin.dart';
import '../model/record_history_list_resp.dart';
import '../widget/simple_waveform_progressbar.dart';

class RecordHistoryPage extends ConsumerStatefulWidget {
  const RecordHistoryPage({super.key});

  @override
  ConsumerState<RecordHistoryPage> createState() => _RecordHistoryPageState();
}

class _RecordHistoryPageState extends ConsumerState<RecordHistoryPage>
    with RecordHistoryMixin, WidgetsBindingObserver {
  @override
  void dispose() {

    refreshController.dispose();
    durationSubscription?.cancel();
    playerCompleteSubscription?.cancel();
    super.dispose();
  }
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getDeviceInfo();
      _fetchHistoryList(true);
      initStream();
      final deviceInfo = ref.watch(deviceInfoProvider);

      DateTime now = DateTime.now();
      int currentYear = now.year;
      int currentMonth = now.month;

      // 获取前一个月的年月
      DateTime previousMonth = DateTime(now.year, now.month - 1);
      // 获取前两个月的年月
      DateTime twoMonthsAgo = DateTime(now.year, now.month - 2);

      ToastUtils.showLoading(status: "获取数据...");
      getDayData(deviceInfo.imei ?? "", currentYear.toString(), currentMonth.toString(), dataCallBack: (List<DateTime> dataArr) {
        trackCalendar = dataArr;
          getDayData(deviceInfo.imei ?? "", previousMonth.year.toString(), previousMonth.month.toString(), dataCallBack: (List<DateTime> dataArr) {
            trackCalendar.addAll(dataArr);
              getDayData(deviceInfo.imei ?? "", twoMonthsAgo.year.toString(), twoMonthsAgo.month.toString(), dataCallBack: (List<DateTime> dataArr) {
                trackCalendar.addAll(dataArr);
                  XLogger.info(trackCalendar);
                ToastUtils.dismissLoading();
              },
              );
            },
          );
        },
      );
    });

    super.initState();
    WidgetsBinding.instance.addObserver(this);

    refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      getDeviceInfo();
      XLogger.info("didChangeAppLifecycleState");
    }
  }


  void initStream() {
    durationSubscription = audioPlayer.onPositionChanged.listen(
      (p) {
        historyList[curPLayIndex].progress =
            p.inSeconds / (historyList[curPLayIndex].duration ?? 1);
        setState(() {});
      },
    );
    XLogger.info("准备检查已读");
    playerCompleteSubscription =
        audioPlayer.onPlayerComplete.listen((event) async {
          XLogger.info("准备检查已读回调");
          XLogger.info(historyList[curPLayIndex].status);

          if (historyList[curPLayIndex].status == 0) {
        final res = await readRecordFile(historyList[curPLayIndex]);
        // if (res.data != null) {
        //   historyList[curPLayIndex].status = 1;
        // }
            if (res.code == 200) {
              historyList[curPLayIndex].status = 1;
            }
      }
      if(isAutoPlay){
        // if(curPLayIndex < historyList.length - 1){
        //   playRecord(historyList[curPLayIndex + 1], curPLayIndex + 1);
        // } else {
        //   setState(() {
        //     curPLayIndex = -1;
        //   });
        // }
        if (curPLayIndex > 0 && curPLayIndex < historyList.length) {
          playRecord(historyList[curPLayIndex - 1], curPLayIndex - 1);
        }else {
          setState(() {
              curPLayIndex = -1;
          });
        }
      } else {
        setState(() {
          curPLayIndex = -1;
        });
      }
    });
  }

  _fetchHistoryList(bool isRefresh) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei == null || deviceInfo.expired == true) {
      setState(() {
        showLoading = false;
        pageNum = 1;
        historyList = <RecordHistoryData>[];
      });
      refreshController.finishRefresh();
      return;
    }
    final queryParams = {
      'pageNum': pageNum,
      'pageSize': 9999,
      "imei": deviceInfo.imei,
      "dateTime": DateUtil.formatDate(selectTime, format: "yyyy-MM-dd")
    };
    final res = await get<RecordHistoryListResp, RecordHistoryListResp>(
        '$newBaseULr/deviceFile/list',
        queryParameters: queryParams,
        decodeType: RecordHistoryListResp());
    setState(() {
      showLoading = false;
    });
    res.when(success: (resp) {
      if (resp.code == 200) {
        XLogger.info(isRefresh);

        if (isRefresh) {
          historyList = resp.rows!.reversed.toList();
          refreshController.finishRefresh();
          pageNum++;

        } else {
          // 判断是否还有数据
          // if (resp.rows!.isEmpty) {
          XLogger.info((resp.total ?? 0));
          XLogger.info(pageNum * 10);

          refreshController.finishLoad(IndicatorResult.noMore);
          return;
          if ((resp.total ?? 0) < (pageNum - 1) * 10) {
            refreshController.finishLoad(IndicatorResult.noMore);
            return;
          } else {
            // pageNum++;
            // historyList.addAll(resp.rows!);
            // refreshController.finishLoad();
          }
        }
        setState(() {});
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取安防列表失败 code: $code msg: $msg');
    });
  }

  _showLoading() {
    if (showLoading) {
      return Container(
        alignment: Alignment.center,
        child: CircularProgressIndicator(
          color: AppTheme.themeConfig.primaryColor,
        ),
      );
    } else {
      return _buildListView();
    }
  }
  _goToVipPage(String chooseTabIndex) {
    context.push('${RouterManager.vipService}?chooseTabIndex=${chooseTabIndex}').then((value){
       getDeviceInfo();
    });
  }

  _kaitonggaoqing() {
    /// 自定义一个弹窗
    showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {

        return Dialog(
          child: Container(
            height: 200,
            width: 300,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                color: AppTheme.themeConfig.greyBgColor
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(height: 1),
                const Text(
                    '您还未开通高清录音模式',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 10),
                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.primaryColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      _goToVipPage("1");
                      Navigator.of(context).pop();
                    },
                    child: const Text('前往开通'),
                  ),
                ),

                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.infoTextColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: const Text('取消'),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
  _winxintishi() {
    /// 自定义一个弹窗
    showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {

        return Dialog(
          child: Container(
            height: 340,
            width: 300,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                color: AppTheme.themeConfig.greyBgColor
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(height: 20),
                Text(
                  '温馨提示，免责声明',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 20),
                const Padding(padding: EdgeInsets.only(left: 20,right: 20, bottom: 0),
                  child: const Text(
                    '   内容不可以传播，不可以用于违法行为。如非法使用导致任何的法律责任均由使用者承担责任，请用户谨慎使用。',
                    style: TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                const Padding(padding: EdgeInsets.only(left: 20,right: 20,top: 0),
                  child: const Text(
                    '   安防拾音功能适用于儿童，老人关爱监护及车辆等贵重物品的防丢防盗措施，用户自愿启动安防拾音功能包括自愿购买增值服务项目。',
                    style: TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                      color: Color(0xffE50012),

                    ),
                  ),
                ),
                const SizedBox(height: 30),

                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.primaryColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      String cmd = deviceDetails?.securityStatus == 1 ? "db,0" : "db,1";
                      changeStatus(cmd, change: (){
                        final deviceInfo = ref.watch(deviceInfoProvider);
                        final data = {
                          "imei": deviceInfo.imei,
                          "securityStatus": deviceDetails?.securityStatus == 1 ? "0" : "1"
                        };
                        setDevice(data: data);
                        context.pop();
                      });
                    },
                    child: const Text('同意，我已知晓风险'),
                  ),
                ),
                const SizedBox(height: 10),

                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.infoTextColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: const Text('暂不开启'),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
  _checkvoice() {
    if (deviceDetails?.securityStatus != 1) { // 如果是关闭状态

      if (deviceDetails?.securityVip == 1) { // 如果是已经购买
        if (deviceDetails?.securityNum == 0 && deviceDetails?.securityDay == 0) {
          _goToVipPage("0");
          return ;
        }
      }else if (isHigh == true && deviceDetails?.highVip != 1){
        _kaitonggaoqing();
        return;
      }else if (deviceDetails?.securityVip == 0) { //如果是未购买
        _goToVipPage("0");
        return ;
      }
      _winxintishi();
    }else {
      String cmd = deviceDetails?.securityStatus == 1 ? "db,0" : "db,1";
      changeStatus(cmd, change: (){
        final deviceInfo = ref.watch(deviceInfoProvider);
        final data = {
          "imei": deviceInfo.imei,
          "securityStatus": deviceDetails?.securityStatus == 1 ? "0" : "1"
        };
        setDevice(data: data);
      });
    }
  }

  _buildListView() {
    return EasyRefresh(
        controller: refreshController,
        onRefresh: () async {
          pageNum = 1;
          _fetchHistoryList(true);
        },
        onLoad: () async {
          _fetchHistoryList(false);
        },
        child: Stack(
          children: [
            // Scrollbar(
            //   controller: _scrollController,
            //   interactive: true,
            //   thumbVisibility: true,
            //   trackVisibility:true,
            //   thickness: 5,
            //   child: _listBuilder(),
            // ),
            _listBuilder(),

            Offstage(
              offstage: historyList.isNotEmpty,
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  '暂无记录',
                  style: TextStyle(
                    fontSize: 16,
                    color: AppTheme.themeConfig.infoTextColor,
                  ),
                ),
              ),
            ),
          ],
        ));
  }

  _listBuilder() {
    return ListView.separated(
        controller: _scrollController,
        padding: const EdgeInsets.only(top: 16, bottom: 16),
        itemCount: historyList.length,
        itemBuilder: (context, index) {
          RecordHistoryData recordHistoryData = historyList[index];
          final dateStr = DateUtil.formatDate(recordHistoryData.createTime!,
              format: 'yyyy-MM-dd HH:mm:ss');
          return GestureDetector(
            onTap: () {
              if (deleteMode) {
                recordHistoryData.selected = !recordHistoryData.selected;
              }
              setState(() {});
            },
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.only(left: deleteMode ? 36 : 12),
                    child: lpText(dateStr, size: 13),
                  ),
                  const SizedBox(height: 4),
                  GestureDetector(
                    onTap: () {
                      if (deleteMode) {
                        recordHistoryData.selected =
                            !recordHistoryData.selected;
                      } else {
                        // if(isAutoPlay && historyList.isNotEmpty){
                        //   playRecord(historyList.first, index);
                        // }
                        playRecord(recordHistoryData, index);
                      }
                      setState(() {});
                    },
                    child: Row(
                      children: [
                        if (deleteMode)
                          Image.asset(
                              recordHistoryData.selected
                                  ? "assets/images/record_history/icon_checked.png"
                                  : "assets/images/record_history/icon_not_check.png",
                              width: 20,
                              height: 20),
                        if (deleteMode) const SizedBox(width: 4),
                        Expanded(
                          child: LayoutBuilder(builder: (context, con) {
                            double w = con.maxWidth *
                                min(
                                    (min(
                                            max(
                                                recordHistoryData.duration ??
                                                    20,
                                                20),
                                            60) /
                                        60),
                                    0.7);
                            return Row(
                              children: [
                                Container(
                                  width: w,
                                  height: 32,
                                  padding: const EdgeInsets.only(left: 1),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(30),
                                      color: recordHistoryData.status == 1
                                          ? const Color(0xfff6f6f6)
                                          : AppTheme.themeConfig.primaryColor),
                                  child: Row(
                                    children: [
                                      Image.asset(
                                          recordHistoryData.status == 1
                                              ? "assets/images/record_history/icon_voice_read.png"
                                              : "assets/images/record_history/icon_voice_unread.png",
                                          width: 30,
                                          fit: BoxFit.fitWidth,
                                          height: 30),
                                      Expanded(
                                          child: Padding(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 20, vertical: 10),
                                        child: WaveProgressBar(
                                          max: 1,
                                          value: recordHistoryData.progress,
                                          activeColor: Colors.black,
                                          inActiveColor:
                                              recordHistoryData.status == 1
                                                  ? Colors.grey
                                                  : Colors.white,
                                          barWidth: 2,
                                          spacing: 1,
                                        ),
                                      ))
                                    ],
                                  ),
                                ),
                                Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 10),
                                    child: lpText(formatDuration(
                                        recordHistoryData.duration ?? 0))),
                                if (recordHistoryData.status != 1)
                                  Padding(
                                      padding: const EdgeInsets.only(right: 10),
                                      child: Container(
                                        width: 6,
                                        height: 6,
                                        decoration: const BoxDecoration(
                                            shape: BoxShape.circle,
                                            color: Colors.red),
                                      )),
                              ],
                            );
                          }),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
          );
        },
        separatorBuilder: (context, index) {
          return const SizedBox(height: 10);
        });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(
          title: const Text('安防录音', style: TextStyle(fontSize: 18)),
          centerTitle: true,
          backgroundColor: AppTheme.themeConfig.navBarColor,
          foregroundColor: AppTheme.themeConfig.primaryColor,
          leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Container(
              height: kToolbarHeight,
              padding: const EdgeInsets.only(top: 8),
              alignment: Alignment.center,
              child: const Text(' <返回',
                  textAlign: TextAlign.center,
                  maxLines: 1,
                  style: TextStyle(color: Colors.black)),
            ),
          ),
          actions: [
            GestureDetector(
              onTap: () {
                _scrollController.animateTo(_scrollController.position.maxScrollExtent, duration: Duration(milliseconds: 300), curve: Curves.easeInOut);
              },
              child: Container(
                margin: const EdgeInsets.only(right: 16),
                height: kToolbarHeight,
                padding: const EdgeInsets.only(top: 8),
                alignment: Alignment.center,
                child: Image.asset(
                    "assets/images/record_history/go_down.jpg",
                    width: 20,
                    height: 20),
              ),
            ),
            GestureDetector(
              onTap: () {
                setState(() {
                  if (deleteMode) {
                    return;
                  }
                  deleteMode = !deleteMode;
                  if (deleteMode) {
                    isAllSelect = false;
                  }
                });
              },
              child: Container(
                margin: const EdgeInsets.only(right: 16),
                height: kToolbarHeight,
                padding: const EdgeInsets.only(top: 8),
                alignment: Alignment.center,
                child: Image.asset(
                    "assets/images/record_history/icon_delete.png",
                    width: 20,
                    height: 20),
              ),
            )
          ],
        ),
        backgroundColor: const Color(0xffC7C8C9),
        body: Column(
          children: [
            buildHeader(),
            Expanded(child: _showLoading()),
            _buildBottom()
          ],
        ));
  }

  Widget _buildBottom() {
    return Container(
    // return SafeArea(
    //     top: false,
        child: deleteMode ? buildDeleteBottom() : buildNormalBottom());
  }

  Widget buildNormalBottom() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topRight: Radius.circular(20), topLeft: Radius.circular(20))),
      child: Column(
        children: [
          Row(
            children: [
              GestureDetector(
                onTap: () async {
                  if (deviceDetails?.highVip == 1) { // 如果是购买高清

                  }else {
                    if (isHigh == false) {
                      _kaitonggaoqing();
                      return;
                    }
                  }
                  String cmd = isHigh ? "gq,0" : "gq,1";
                  changeStatus(cmd, change: (){
                    final deviceInfo = ref.watch(deviceInfoProvider);
                    final data = {
                      "imei": deviceInfo.imei,
                      "highStatus": isHigh ? "0" : "1"
                    };
                    setDevice(data: data, voidCallback: (){
                      setState(() {
                        isHigh = !isHigh;
                      });
                    });
                  });
                },
                child: Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                      color: AppTheme.themeConfig.primaryColor,
                      borderRadius: BorderRadius.circular(20)),
                  child: Row(
                    children: [
                      Image.asset(
                          isHigh
                              ? "assets/images/record_history/icon_checked.png"
                              : "assets/images/record_history/icon_not_check.png",
                          width: 20,
                          height: 20),
                      const SizedBox(width: 6),
                      lpText("高清录音", color: Colors.white)
                    ],
                  ),
                ),
              ),
              GestureDetector(
                onTap: showBottomDialog,
                child: Container(
                  margin: const EdgeInsets.only(left: 10),
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                      color: AppTheme.themeConfig.primaryColor,
                      borderRadius: BorderRadius.circular(20)),
                  child: lpText("设置灵敏度", color: Colors.white),
                ),
              ),
              const Expanded(child: Center()),
              GestureDetector(
                onTap: () {
                  setState(() {
                    isAutoPlay = !isAutoPlay;
                  });
                },
                child: Row(
                  children: [
                    isAutoPlay
                        ? Image.asset(
                            "assets/images/record_history/icon_auto_play.png",
                            width: 18,
                            height: 18)
                        : Container(
                            width: 18,
                            height: 18,
                            decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                border: Border.all(
                                    color: const Color(0xff231815), width: 1)),
                          ),
                    const SizedBox(width: 4),
                    lpText("自动播放", size: 14)
                  ],
                ),
              )
            ],
          ),
          const SizedBox(height: 10),
          lpText(
              "温馨提示：\n        安防拾音功能适用于儿童，老人关爱监护及车辆等贵重物品的防丢防盗措施。\n        用户自愿启动安防拾音功能包括自愿购买增值服务项目，内容不可以传播，不可以用于违法行为。如非法使用导致任何的法律责任均由使用者承担责任，请用户谨慎使用。",
              size: 13),
          GestureDetector(
            onTap: _checkvoice,
            child: Container(
              alignment: Alignment.center,
              width: MediaQuery.of(context).size.width,
              margin:
              const EdgeInsets.only(left: 30, right: 30, top: 10, bottom: 16),
              padding: const EdgeInsets.symmetric(vertical: 8),
              decoration: BoxDecoration(
                  color: AppTheme.themeConfig.primaryColor,
                  borderRadius: BorderRadius.circular(20)),
              child: lpText(
                  deviceDetails?.securityStatus == 1 ? "关闭安防录音" : "开始安防录音",
                  color: Colors.white,
                  size: 16),
            ),
          )
        ],
      ),
    );
  }

  void showBottomDialog() {
    Dialogs.bottomMaterialDialog(
        context: context,
        customView: Column(
          children: [
            Stack(
              alignment: Alignment.center,
              children: [
                Container(
                  alignment: Alignment.center,
                  width: MediaQuery.of(context).size.width,
                  padding: const EdgeInsets.only(top: 20, bottom: 16),
                  child: lpText("录音灵敏度设置", size: 20),
                ),
                Positioned(
                  top: 16,
                  right: 16,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.of(context).pop();
                    },
                    child: SizedBox(
                      width: 40,
                      height: 40,
                      child: lpText('取消',
                          size: 14, color: AppTheme.themeConfig.primaryColor),
                    ),
                  ),
                )
              ],
            ),
            StatefulBuilder(builder: (context, setState) {
              return Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  children: [
                    lpText("低"),
                    Expanded(
                        child: Slider(
                          activeColor: AppTheme.themeConfig.primaryColor,
                          value: sliderProgress,
                          max: 1,
                          divisions: 3,
                          onChanged: (double value) {
                            // String cmd = "dbcs,${value == 0.0 ? 100 : (value == 1.0 ? 50 : 80)},${value == 0.0 ? 5 : (value == 1.0 ? 1 : 2)}";
                            // changeStatus(cmd, change: (){
                            //   final deviceInfo = ref.watch(deviceInfoProvider);
                            //   final data = {
                            //     "imei": deviceInfo.imei,
                            //     "recordGears": value == 1.0 ? "1" : (value == 0.5 ? "2" : "5")
                            //   };
                            //   XLogger.info(cmd);
                            //
                            //   setDevice(data: data, voidCallback: (){
                            //     setState(() {
                            //       sliderProgress = value;
                            //     });
                            //   });
                            // });
                          },
                          onChangeEnd: (double value) {
                            XLogger.info(value);

                            String cmd;
                            int recordGears;
                            if (value == 0.0) {
                              cmd = "dbcs,140,5";
                              recordGears = 5;
                            }else if (value > 0.3 && value < 0.6) {
                              cmd = "dbcs,110,4";
                              recordGears = 4;
                            }else if (value > 0.6 && value < 1) {
                              cmd = "dbcs,80,2";
                              recordGears = 2;
                            }else {
                              cmd = "dbcs,1,1";
                              recordGears = 1;
                            }
                            XLogger.info(cmd);
                            XLogger.info(recordGears);

                            changeStatus(cmd, change: (){
                              final deviceInfo = ref.watch(deviceInfoProvider);
                              final data = {
                                "imei": deviceInfo.imei,
                                "recordGears": recordGears,
                              };

                              setDevice(data: data, voidCallback: (){
                                setState(() {
                                  sliderProgress = value;
                                });
                              });
                            });
                          },
                        )),
                    lpText("高")
                  ],
                ),
              );
            })
          ],
        ));
  }

  Widget buildDeleteBottom() {
    return Column(
      children: [
        Row(
          children: [
            GestureDetector(
              onTap: selectAll,
              child: Padding(
                  padding: const EdgeInsets.only(
                      left: 10, right: 10, top: 16, bottom: 16),
                  child: Row(
                    children: [
                      lpText("全选"),
                      const SizedBox(width: 4),
                      Image.asset(
                          isAllSelect
                              ? "assets/images/record_history/icon_checked.png"
                              : "assets/images/record_history/icon_not_check.png",
                          width: 20,
                          height: 20)
                    ],
                  )),
            ),
            Expanded(
                child: lpText(
                    "已选择${historyList.where((element) => element.selected).length}条"))
          ],
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 10),
          child: Row(
            children: [
              Expanded(
                  child: GestureDetector(
                onTap: cancelDeleteMode,
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(30),
                      color: Colors.transparent,
                      border: Border.all(
                          width: 1, color: AppTheme.themeConfig.primaryColor)),
                  child: lpText("取消",
                      size: 16, color: AppTheme.themeConfig.primaryColor),
                ),
              )),
              const SizedBox(width: 20),
              Expanded(
                  child: GestureDetector(
                onTap: () {
                  List<int?> fileId = historyList
                      .where((e) => e.selected)
                      .map((e) => e.fileId)
                      .toList();
                  if (fileId.isEmpty) {
                    ToastUtils.showToast("请选择一条录音");
                    return;
                  }
                  ToastUtils.showDeleteDialog(context,
                      confirmCallback: deleteRecord);
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(30),
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                  child: lpText("确认删除", size: 16, color: Colors.white),
                ),
              )),
            ],
          ),
        )
      ],
    );
  }
  Widget _taocanyuliang() {
    if ((deviceDetails?.securityDay ?? 0) > 0) {
     return lpText("余${deviceDetails?.securityDay ??0}天${deviceDetails?.securityNum ??0}条");

    }else {
     return lpText("余${deviceDetails?.securityNum ??0}条");
    };
  }
  Widget buildHeader() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    return Container(
      color: const Color(0xffDADBDB),
      child: Row(
        children: [
          const SizedBox(width: 20),
          GestureDetector(  // 时间控件
            onTap: showDateSelect,
            child: Row(
              children: [
                lpText(DateUtil.formatDate(selectTime, format: "yyyy-MM-dd")),
                const Icon(
                  Icons.keyboard_arrow_down,
                )
              ],
            ),
          ),
          const Expanded(child: Center()),
          _taocanyuliang(),  // 套餐余量

          GestureDetector(
            onTap: (){
              _goToVipPage("0");
            },
            child: Container(
              alignment: Alignment.center,
              margin: const EdgeInsets.symmetric(vertical: 6, horizontal: 10),
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
              decoration: BoxDecoration(
                  color: AppTheme.themeConfig.primaryColor,
                  borderRadius: BorderRadius.circular(10)),
              child: lpText("购买条数", color: Colors.white),
            ),
          )
        ],
      ),
    );
  }
  Widget? _dayBuilder({
    required date,
    textStyle,
    decoration,
    isSelected,
    isDisabled,
    isToday,
  }) {
    Widget? dayWidget;

    // 如果小于用户最小日期，则将文字颜色设置为灰色

    if (date.isBefore(DateTime.now().subtract(const Duration(days: 60)))) {
      textStyle = textStyle.copyWith(color: AppTheme.themeConfig.infoTextColor);
    } else {
      textStyle =
          textStyle.copyWith(color: AppTheme.themeConfig.primaryTextColor);
    }

    // 只处理trackCalendar中的日期
    if (trackCalendar.isEmpty || !trackCalendar.contains(date)) {
      dayWidget = Container(
        decoration: decoration,
        alignment: Alignment.center,
        child: Text(
          MaterialLocalizations.of(context).formatDecimal(date.day),
          style: textStyle,
        ),
      );
      return dayWidget;
    }
    dayWidget = Container(
      decoration: decoration,
      alignment: Alignment.center,
      child: Center(
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Text(
              MaterialLocalizations.of(context).formatDecimal(date.day),
              style: textStyle,
            ),
            Padding(
              padding: const EdgeInsets.only(top: 27.5),
              child: Container(
                height: 4,
                width: 4,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: isSelected == true ? Colors.white : Colors.red[500],
                ),
              ),
            ),
          ],
        ),
      ),
    );

    return dayWidget;
  }
  void showDateSelect() {
    final BuildContext dialogContext = context; // 保存有效的 context

    if (!isRefreshTrackCalendar) {
      // await loadTrackCalendarData();
    }
    var config = CalendarDatePicker2WithActionButtonsConfig(
      // 不能选择今天之后的日期
      lastDate: DateTime.now(),
      // 只能选择最近60天的日期
      firstDate:DateTime.now().subtract(Duration(days: 60)),
      dayBuilder: _dayBuilder,
    );
    showDialog(context: dialogContext, builder: (context) {
      return Dialog(
        insetPadding: const EdgeInsets.symmetric(
            horizontal: 16.0, vertical: 24.0),
        backgroundColor: Theme.of(context).canvasColor,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        clipBehavior: Clip.antiAlias,
        child: SizedBox(
          width: 325,
          height: max(400, 410),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CalendarDatePicker2WithActionButtons(
                value: calendarValue,
                config: config.copyWith(openedFromDialog: false),
                onValueChanged: (value) {
                  XLogger.info(value);
                  if (value.isNotEmpty) {
                    DateTime chooseDate = value[0]!;
                    XLogger.info(chooseDate);
                    if (chooseDate != null) {
                      DateTime startTime = DateTime.now().subtract(const Duration(days: 15));
                      String content = "超出可查询天数，请购买录音恢复套餐";
                      if(deviceDetails?.playbackVip == 1){
                        startTime = DateTime.now().subtract(const Duration(days: 60));
                        content = "超出最大可查询天数";
                      }
                      if(chooseDate.isBefore(startTime)){
                        XLogger.info("去支付买恢复套餐");
                        XLogger.info(context);

                        ToastUtils.showCheckDateDialog(context, content: content, confirmCallback: (){
                          // if(deviceDetails?.playbackVip != 1){
                          // context.push('${RouterManager.vipService}?chooseTabIndex=2');
                          // }
                          _goToVipPage("2");
                        });

                      }else {
                        selectTime = chooseDate;
                        pageNum = 1;
                        _fetchHistoryList(true);
                        setState(() {
                          calendarValue = value;
                        });
                        Navigator.pop(context);
                      }
                    }else {

                    }
                  }
                },
                onOkTapped: () {
                  XLogger.info("onOkTapped");
                },
                onCancelTapped: () {
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        ),
      );
    });


  }
}
